//
//  BannerAdCellModel.swift
//  iPhone
//
//  Created by Toj on 5/24/23.
//

import UIKit
import GoogleMobileAds

class BannerAdCellModel: NSObject {
    private var _defaultSize = CGSize.def_cipher
    private var _showSize = CGSize(width: .sr_width, height: 100)
    var _cellSize: CGSize {
        return isSetNeedsLayout ? _showSize : _defaultSize
    }
    
    private(set) var number = ""
    
    private(set) var adUnitID = ""
    
    // 是否需要更新布局
    var isSetNeedsLayout = false
    var isRequest = false
    
    var adView: UIView?
    var _complete: ((_ cellModel: BannerAdCellModel)->Void)?
    
    init(_ model: BannerAdModel) {
        super.init()
        
        number = String(model.index)
        // requestAdInfo()
    }
}

extension BannerAdCellModel {
    func loadAd() {
        let size = GADAdSizeFromCGSize(_showSize)
        let _adView = GADBannerView(adSize: size)
        adView = _adView
        _adView.adUnitID = adUnitID
        _adView.delegate = self
        _adView.rootViewController = UIViewController.vc_currentNavigationTopViewController
        _adView.load(GADRequest())
        ///view.isAutoloadEnabled = true
    }
    
    func requestAdInfo(complete: ((_ cellModel: BannerAdCellModel)->Void)?) {
        _complete = complete
        DispatchQueue.main.asyncAfter(deadline: .now()+1) {
            self.response()
        }
    }
    
    func response() {
        isRequest = true
        let count = kBannerAdUnitIDs.count
        let unitIDIndex = Int(arc4random_uniform(UInt32(count)))
        adUnitID = kBannerAdUnitIDs[unitIDIndex]
        loadAd()
    }
    
    func resetCell() {
        adView?.removeFromSuperview()
        adView = nil
        isRequest = false
        isSetNeedsLayout = false
    }
}

extension BannerAdCellModel: GADBannerViewDelegate {
    
    func bannerViewDidReceiveAd(_ bannerView: GADBannerView) {
        let adUnitID = bannerView.adUnitID ?? ""
        print("-->toj: func:\(#function), adUnitID:\(adUnitID)")
        isSetNeedsLayout = true
        _complete?(self)
    }
    
    func bannerView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: Error) {
        let adUnitID = bannerView.adUnitID ?? ""
        print("-->toj: func:\(#function), adUnitID:\(adUnitID), size:\(bannerView.adSize)")
        print("-->toj: func: \(#function) msg: \(error.localizedDescription)")
        isSetNeedsLayout = false
        _complete?(self)
    }
    
    func bannerViewDidRecordImpression(_ bannerView: GADBannerView) {
    }
}

extension BannerAdCellModel: UICollectionViewCellModelProtocol {
    
    /// 注册类
    static var registerCell: UICollectionViewCell.Type {
        return BannerCollectionViewCell.self
    }
    
    var cellSize: CGSize {
        return _cellSize
    }
}
